import DateUtils from '../DateUtils';
import FsUtils from '../FsUtils';

export default class ImageToAlbumUtils {
    private static instance: ImageToAlbumUtils;
    public static getInstance() {
        if (!this.instance) {
            this.instance = new ImageToAlbumUtils();
        }
        return this.instance;
    }


    private constructor() {

    }
    /**
     * 保存图片到相册
     * 支持网络图片
     * @param path 图片路径
     * @param group 分组名
     * 
     */
    public save(path: string, group?: string) {
        return new Promise<boolean>((resolve) => {
            const groupName = group || api.appName + DateUtils.getInstance().toStr(Date.now(), 'yyyymmddhhiiss');
            if (path.substr(0, 4) === 'http') {
                api.imageCache({
                    url: path,
                    policy: 'cache_only',
                    thumbnail: false
                }, async (ret) => {
                    if (!ret.status) {
                        resolve(false);
                        return;
                    }
                    const ios = api.systemType === 'ios';
                    if (ios) {
                        this.saveMediaToAlbum({ path: ret.url, groupName }).then(resolve);
                        return;
                    }
                    const newPath = ret.url + '.png';
                    const exits = await FsUtils.getInstance().exist({ path: newPath });

                    if (exits) {
                        this.saveMediaToAlbum({ path: newPath, groupName }).then(resolve);
                        return;
                    }
                    const result = await FsUtils.getInstance().rename({
                        oldPath: ret.url,
                        newPath
                    });
                    if (!result.status) {
                        resolve(false);
                        return;
                    }
                    this.saveMediaToAlbum({ path: newPath, groupName }).then(resolve);
                });
                return;
            }
            this.saveMediaToAlbum({ path, groupName }).then(resolve);
        });
    }

    /**
     * 保存到相册
     * @param params 
     */
    private saveMediaToAlbum(params: {
        path: string,
        groupName: string
    }) {
        return new Promise<boolean>((resolve) => {
            api.saveMediaToAlbum(params, (ret) => {
                resolve(ret.status);
            });
        });
    }
}
